import { CustomEnum, AuthButton, Dialog } from 'custom/index'
import { ElMessage, ElMessageBox } from 'element-plus'
import { exportExcel } from '@/utils/common'

function getExportExcelParams(ctx: any): { url: any, [prop: string]: any } {
  const { route, props } = ctx
  const url = route.name
  return { url, condition: props.query, sort: props.sort }
}

export default class PageListAuthButton extends AuthButton {
  public static name: CustomEnum = 'PageListAuthButton';

  protected static props = {
    query: {
      type: Object,
      default: () => ({})
    },
    page: {
      type: Object,
      default: () => ({})
    },
    sort: {
      type: Object,
      default: () => ({})
    },
  }

  addRow<T extends Dialog>(dialog: T | Function ) {
    this.action(({ _c }) => {
      _c.dispatch('ListPage', 'addRow', dialog)
    })
    return this
  }

  batchDeleteRows<T extends Dialog>(dialog: T | Function ) {
    this.action(({ _c }) => {
      _c.dispatch('ListPage', 'batchDeleteRows', dialog)
    })
    return this
  }

  removeRows(api: (ids: any) => Promise<any>, getIds?: (selection: any[]) => any[]) {
    return this.batchDeleteRows(async ({ ids, selection }) => {
      const data = getIds ? getIds(selection) : ids
      await ElMessageBox.confirm('是否确定删除？', '提示')
      await api(data)
      ElMessage.success('操作成功')
    })
  }

  exportExcel(getParams = getExportExcelParams) {
    return this.action((ctx) => {
      const parms = getParams(ctx)
      exportExcel(parms)
    })
  }

  exportData(api: any, filename?: string) {
    return this.action((ctx) => {
      const props = ctx.props
      const { query, page } = props
      const params = {
        page: {
          index: page.page,
          size: page.size
        },
        condition: query
      }
      api(params).then(res => {
        const reader =  new FileReader()
        reader.readAsDataURL(res.data)
        reader.onload = (e) => {
          let name = filename
          const contentDisposition = res.headers.get('Content-Disposition');
          if (!name && contentDisposition) {
            // 解析Content-Disposition头来提取文件名
            name = contentDisposition.split(`attachment;filename*=utf-8''`)[1].trim().replace(/\"/g, '');
            const [n, h] = name.split('.')
            name = `${decodeURIComponent(n)}.${h}`
          }

          const a = document.createElement('a')
          a.download = name
          a.href = e.target.result as string
          document.body.append(a)
          a.click()
          document.body.removeChild(a)
        }
      })
    })
  }

  end() {
    return this.upto('PageListAuthButtonGroup')
  }
}
